package com.ruoyi.mp.service.impl;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.db.domain.system.MpCashApply;
import com.ruoyi.db.domain.system.MpClient;
import com.ruoyi.db.domain.system.PcGoldConfig;
import com.ruoyi.db.domain.system.PcSilverConfig;
import com.ruoyi.db.domain.web.MpClientTransfer;
import com.ruoyi.db.domain.web.MpIncomeRecord;
import com.ruoyi.db.mapper.system.MpClientMapper;
import com.ruoyi.db.mapper.system.PcGoldConfigMapper;
import com.ruoyi.db.mapper.system.PcSilverConfigMapper;
import com.ruoyi.db.mapper.web.MpClientTransferMapper;
import com.ruoyi.db.mapper.web.MpIncomeRecordMapper;
import com.ruoyi.mp.service.IMpClientTransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户转账记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-07-27
 */
@Service
@Transactional(rollbackOn = Exception.class)
public class MpClientTransferServiceImpl implements IMpClientTransferService
{
    @Autowired
    private MpClientTransferMapper mpClientTransferMapper;
    @Autowired
    private PcGoldConfigMapper pcGoldConfigMapper;
    @Autowired
    private MpClientMapper mpClientMapper;
    @Autowired
    private MpIncomeRecordMapper mpIncomeRecordMapper;
    @Autowired
    private PcSilverConfigMapper pcSilverConfigMapper;

    /**
     * 查询用户转账记录
     * 
     * @param id 用户转账记录主键
     * @return 用户转账记录
     */
    @Override
    public MpClientTransfer selectMpClientTransferById(Long id)
    {
        return mpClientTransferMapper.selectMpClientTransferById(id);
    }

    /**
     * 查询用户转账记录列表
     * 
     * @param mpClientTransfer 用户转账记录
     * @return 用户转账记录
     */
    @Override
    public List<MpClientTransfer> selectMpClientTransferList(MpClientTransfer mpClientTransfer) throws ParseException {
        if(StringUtils.isNotBlank(mpClientTransfer.getStartTime())){
            SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM-");
            Date date = new Date();
            date = sdfTwo.parse(mpClientTransfer.getStartTime()+"-");
            Calendar a = Calendar.getInstance();
            a.setTime(date);
            a.set(Calendar.DATE, 1);//把日期设置为当月第一天
            a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
            //当月有多少天
            int maxDate = a.get(Calendar.DATE);

            String startTime = sdfTwo.format(date) + "01 00:00:00";
            String endTime = sdfTwo.format(date) + maxDate + " 23:59:59";
            mpClientTransfer.setStartTime(startTime);
            mpClientTransfer.setEndTime(endTime);
        }
        List<MpClientTransfer> list = mpClientTransferMapper.selectMpClientTransferListByMonth(mpClientTransfer);
        List<MpClientTransfer> listMy = list.stream().filter(e->e.getClientId().equals(mpClientTransfer.getClientId())).collect(Collectors.toList());
        List<MpClientTransfer> returnList =new ArrayList<>();

        for (MpClientTransfer t: listMy) {
            MpClient accept = mpClientMapper.selectMpClientByClientId(t.getAcceptClientId());
            t.setClientMobile(accept.getMobile());
            t.setClientName(accept.getName());
            t.setIsIncome(false);
        }
        returnList.addAll(listMy);
        List<MpClientTransfer> listOthers = list.stream().filter(e->e.getAcceptClientId().equals(mpClientTransfer.getClientId())).collect(Collectors.toList());
        for (MpClientTransfer t: listOthers) {
            MpClient my = mpClientMapper.selectMpClientByClientId(t.getClientId());
            t.setClientMobile(my.getMobile());
            t.setClientName(my.getName());
            t.setIsIncome(true);
        }
        returnList.addAll(listOthers);
        return returnList;

    }

    /**
     * 新增用户转账记录
     * 
     * @param mpClientTransfer 用户转账记录
     * @return 结果
     */
    @Override
    public void insertMpClientTransfer(MpClientTransfer mpClientTransfer, MpClient client)
    {
        if(StringUtils.isBlank(client.getName())){
            throw new ServiceException("请先设置昵称");
        }
        MpClient accpet =mpClientMapper.selectMpClientByClientId(mpClientTransfer.getAcceptClientId());
        if(accpet==null){
            throw new ServiceException("转账用户不存在");
        }
        if(StringUtils.isBlank(accpet.getName())){
            throw new ServiceException("对方尚未设置昵称，无法接收转账，请通知对方先设置昵称");
        }
        if(mpClientTransfer.getBeanType().equals("1")){
            PcGoldConfig pcGoldConfig = new PcGoldConfig();
            List<PcGoldConfig> configs = pcGoldConfigMapper.selectPcGoldConfigList(pcGoldConfig);
            if(configs.size()>0){
                PcGoldConfig config = configs.get(0);
                if(config!=null&&config.getTransferApply().equals("0")){
                    throw new ServiceException("系统暂时不能转账");
                }
            }
            BigDecimal goldLimitReal = new BigDecimal(0);
            BigDecimal goldLimit = client.getGoldTransferLimit();
            if(goldLimit==null){
                PcGoldConfig transferConfig = new PcGoldConfig();
                List<PcGoldConfig> tConfigs = pcGoldConfigMapper.selectPcGoldConfigList(transferConfig);
                if(tConfigs.size()>0){
                    PcGoldConfig config = tConfigs.get(0);
                    goldLimitReal=config.getTransferLimit();
                }
            }else {
                goldLimitReal =goldLimit;
            }
            MpClientTransfer clientTransfer = new MpClientTransfer();
            clientTransfer.setClientId(client.getClientId());
            clientTransfer.setBeanType("1");
            String startTime =getTodayStartTime();
            String endTime = getTodayEndTime();
            clientTransfer.setStartTime(startTime);
            clientTransfer.setEndTime(endTime);
            List<MpClientTransfer> oldList = mpClientTransferMapper.selectMpClientTransferListByTime(clientTransfer);
            BigDecimal cashSum = oldList.stream().filter(e->e.getAmount()!=null).collect(Collectors.toList()).stream().map( MpClientTransfer::getAmount ).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
            BigDecimal cashToday = cashSum.add(mpClientTransfer.getAmount());
            if(cashToday.compareTo(goldLimitReal)>0){
                throw new ServiceException("今日转账额度已达上限");
            }
            //转账比例
            BigDecimal chargeSum = new BigDecimal(0);
            PcGoldConfig chargeConfig = new PcGoldConfig();
            List<PcGoldConfig> charges = pcGoldConfigMapper.selectPcGoldConfigList(chargeConfig );
            if(charges.size()>0){
                PcGoldConfig config = charges.get(0);
                if(config.getTransferRate()!=null){
                    chargeSum=mpClientTransfer.getAmount().multiply(config.getTransferRate()).setScale( 2, BigDecimal.ROUND_HALF_UP );
                }
            }
            //添加转账记录
            BigDecimal myGold = client.getGoldBeanBalance();
            BigDecimal mySum = (myGold==null?new BigDecimal(0):myGold).subtract(mpClientTransfer.getAmount())
                    .subtract(chargeSum);
            if(mySum.compareTo(new BigDecimal(0))<0){
                throw new ServiceException("用户金藻余额不足");
            }
            mpClientTransfer.setChargeAmount(chargeSum);
            mpClientTransfer.setTransferTime(new Date());
            if(mpClientTransferMapper.insertMpClientTransfer(mpClientTransfer)>0){
                //修改用户金额，添加收支记录
                MpClient accept = mpClientMapper.selectMpClientByClientId(mpClientTransfer.getAcceptClientId());
                BigDecimal acceptGold = accept.getGoldBeanBalance();
                BigDecimal acceptSum = (acceptGold==null?new BigDecimal(0):acceptGold).add(mpClientTransfer.getAmount());
                accept.setGoldBeanBalance(acceptSum);
                if(mpClientMapper.updateMpClient(accept)>0){
                    client.setGoldBeanBalance(mySum);
                    MpIncomeRecord record = new MpIncomeRecord();
                    record.setClientId(mpClientTransfer.getAcceptClientId());
                    record.setCreateTime(new Date());
                    record.setIsIncome(1l);
                    record.setAmount(mpClientTransfer.getAmount());
                    record.setContent("收到转账");
                    record.setType(1l);
                    record.setCurrentBalance(accept.getGoldBeanBalance());
                    mpIncomeRecordMapper.insertMpIncomeRecord(record);

                    if(mpClientMapper.updateMpClient(client)>0){
                        MpIncomeRecord recordReturn = new MpIncomeRecord();
                        recordReturn.setClientId(client.getClientId());
                        recordReturn.setCreateTime(new Date());
                        recordReturn.setIsIncome(0l);
                        recordReturn.setAmount(mpClientTransfer.getAmount().add(chargeSum));
                        recordReturn.setContent("转账及手续费");
                        recordReturn.setType(1l);
                        recordReturn.setCurrentBalance(client.getGoldBeanBalance());
                        mpIncomeRecordMapper.insertMpIncomeRecord(recordReturn);
                    }
                }
            }
        }
        if(mpClientTransfer.getBeanType().equals("2")){
            PcSilverConfig pcSilverConfig = new PcSilverConfig();
            List<PcSilverConfig> configs = pcSilverConfigMapper.selectPcSilverConfigList(pcSilverConfig);
            if(configs.size()>0){
                PcSilverConfig config = configs.get(0);
                if(config!=null&&config.getTransferApply().equals("0")){
                    throw new ServiceException("系统暂时不能转账");
                }
            }
            BigDecimal silverLimitReal = new BigDecimal(0);
            BigDecimal silverLimit = client.getSilverTransferLimit();
            if(silverLimit==null){
                PcSilverConfig transferConfig = new PcSilverConfig();
                List<PcSilverConfig> tConfigs = pcSilverConfigMapper.selectPcSilverConfigList(transferConfig);
                if(tConfigs.size()>0){
                    PcSilverConfig config = tConfigs.get(0);
                    silverLimitReal=config.getTransferLimit();
                }
            }else {
                silverLimitReal =silverLimit;
            }
            MpClientTransfer clientTransfer = new MpClientTransfer();
            clientTransfer.setClientId(client.getClientId());
            clientTransfer.setBeanType("2");
            String startTime = getTodayStartTime();
            String endTime = getTodayEndTime();
            clientTransfer.setStartTime(startTime);
            clientTransfer.setEndTime(endTime);
            List<MpClientTransfer> oldList = mpClientTransferMapper.selectMpClientTransferListByTime(clientTransfer);
            BigDecimal cashSum = oldList.stream().map( MpClientTransfer::getAmount ).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
            BigDecimal cashToday = cashSum.add(mpClientTransfer.getAmount());
            if(cashToday.compareTo(silverLimitReal)>0){
                throw new ServiceException("今日转账额度已达上限");
            }
            //转账比例
            BigDecimal chargeSum = new BigDecimal(0);
            PcSilverConfig chargeConfig = new PcSilverConfig();
            List<PcSilverConfig> charges = pcSilverConfigMapper.selectPcSilverConfigList(chargeConfig);
            if(charges.size()>0){
                PcSilverConfig config = charges.get(0);
                if(config.getTransferRate()!=null){
                    chargeSum=mpClientTransfer.getAmount().multiply(config.getTransferRate()).setScale( 2, BigDecimal.ROUND_HALF_UP );
                }
            }
            //添加转账记录
            BigDecimal myGold = client.getSilverBeanBalance();
            BigDecimal mySum = (myGold==null?new BigDecimal(0):myGold).subtract(mpClientTransfer.getAmount())
                    .subtract(chargeSum);
            if(mySum.compareTo(new BigDecimal(0))<0){
                throw new ServiceException("用户金藻余额不足");
            }
            mpClientTransfer.setChargeAmount(chargeSum);
            mpClientTransfer.setTransferTime(new Date());
            if(mpClientTransferMapper.insertMpClientTransfer(mpClientTransfer)>0){
                //修改用户金额，添加收支记录
                MpClient accept = mpClientMapper.selectMpClientByClientId(mpClientTransfer.getAcceptClientId());
                BigDecimal acceptGold = accept.getSilverBeanBalance();
                BigDecimal acceptSum = (acceptGold==null?new BigDecimal(0):acceptGold).add(mpClientTransfer.getAmount());
                accept.setSilverBeanBalance(acceptSum);
                if(mpClientMapper.updateMpClient(accept)>0){
                    client.setSilverBeanBalance(mySum);
                    MpIncomeRecord record = new MpIncomeRecord();
                    record.setClientId(mpClientTransfer.getAcceptClientId());
                    record.setCreateTime(new Date());
                    record.setIsIncome(1l);
                    record.setAmount(mpClientTransfer.getAmount());
                    record.setContent("收到转账");
                    record.setType(2l);
                    record.setCurrentBalance(accept.getGoldBeanBalance());
                    mpIncomeRecordMapper.insertMpIncomeRecord(record);

                   if(mpClientMapper.updateMpClient(client)>0){
                       MpIncomeRecord recordReturn = new MpIncomeRecord();
                       recordReturn.setClientId(client.getClientId());
                       recordReturn.setCreateTime(new Date());
                       recordReturn.setIsIncome(0l);
                       recordReturn.setAmount(mpClientTransfer.getAmount().add(chargeSum));
                       recordReturn.setContent("转账及手续费");
                       recordReturn.setType(2l);
                       recordReturn.setCurrentBalance(client.getGoldBeanBalance());
                       mpIncomeRecordMapper.insertMpIncomeRecord(recordReturn);
                   }
                }
            }
        }
    }

    @Override
    public BigDecimal getTransferRate() {
        //转账比例
        PcGoldConfig chargeConfig = new PcGoldConfig();
        List<PcGoldConfig> charges = pcGoldConfigMapper.selectPcGoldConfigList(chargeConfig );
        if(charges.size()>0){
            PcGoldConfig config = charges.get(0);
            return config.getTransferRate();
        }
        return null;
    }

    @Override
    public BigDecimal getTransferSliverRate() {
        //转账比例
        PcSilverConfig chargeConfig = new PcSilverConfig();
        List<PcSilverConfig> charges=pcSilverConfigMapper.selectPcSilverConfigList(chargeConfig);
        if(charges.size()>0){
            PcSilverConfig config = charges.get(0);
            return config.getTransferRate();
        }
        return null;
    }

    public String getTodayStartTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String todayStartTime=sdf.format(new Date());
        return  todayStartTime;
    }
    public String getTodayEndTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar todayCalendar = Calendar.getInstance();
        todayCalendar.add(Calendar.DATE,1); // 获取明天00:00:00
        //今天结束时间
        Date end = todayCalendar.getTime();
        String todayEndTime=sdf.format(end);
        return todayEndTime;
    }
}
